//app.js
var utils = require('./common/util');

App({
  onLaunch: function () {
    this.getCatalog();
  },

  getCatalog: function(cb){
    var url = 'https://v.share-h5.com/bible-server/catalog.php';
    this.requestData('catalog', url, cb);
  },

  getUserInfo:function(cb){
    var that = this;
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //调用登录接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })

    }
  },

  requestData: function (key, url, callback){

    var isLocalStorage = this.globalData.storageType === 'localStorage';
    var storageObject = this.globalData;

    var data;
    if(isLocalStorage){
      data = wx.getStorageSync(key);
    }else{
      data = storageObject[key];
    }

    if(data){
      callback && callback(data);
    }else{
      wx.request({
        url: url,
        header: {
          'content-type': 'application/json'
        },
        success: function(res) {
          if(isLocalStorage){
            wx.setStorageSync(key, res.data);
          }else{
            storageObject[key] = res.data;
          }
          
          callback && callback(res.data);
        }
      });		
    }
    
  },

  globalData:{
    userInfo: null,
    catalog: null,
    storageType: 'appGlobalData' // appGlobalData
  }
})